/*
 * 版权所有 2009-2022山东新北洋信息技术股份有限公司 保留所有权利。
 */
package online.xuping.thousandsOfWorlds.common.snowflake;

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.beanutils.BeanUtils;
import org.apache.ibatis.executor.Executor;
import org.apache.ibatis.mapping.MappedStatement;
import org.apache.ibatis.mapping.SqlCommandType;
import org.apache.ibatis.plugin.Interceptor;
import org.apache.ibatis.plugin.Intercepts;
import org.apache.ibatis.plugin.Invocation;
import org.apache.ibatis.plugin.Plugin;
import org.apache.ibatis.plugin.Signature;
import org.springframework.util.ReflectionUtils;

import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.util.List;
import java.util.Map;

/**
 * 主键替换拦截器
 * 拦截insert语句，替换实体类里面的id值
 *
 * @author dongyinggang
 * @date 2022/10/20 17:48
 * @copyright 2022 山东新北洋信息技术股份有限公司. All rights reserved
 */
@Intercepts({@Signature(type = Executor.class, method = "update", args = {MappedStatement.class, Object.class})})
@Slf4j
public class PrimaryKeyInterceptor implements Interceptor {

    public static final int TWO_INT = 2;
    //主键生成策略
    private SnowflakeIdWorker snowflakeIdWorker;

    private String primaryKey;

    public PrimaryKeyInterceptor() {
        //空构造
    }

    /**
     * 拦截器，进行主键的雪花id生成
     *
     * @param invocation : 拦截的位置
     * @return {@link Object }
     * @author dongyinggang
     * @date 2022/10/21 14:03
     **/
    @Override
    public Object intercept(Invocation invocation) throws Throwable {

        Object[] args = invocation.getArgs();
        if (args == null || args.length != TWO_INT) {
            return invocation.proceed();
        } else {
            MappedStatement ms = (MappedStatement) args[0];
            // 操作类型
            SqlCommandType sqlCommandType = ms.getSqlCommandType();
            // 只处理insert操作
            if (sqlCommandType == SqlCommandType.INSERT) {
                if (args[1] instanceof Map) {
                    // //当参数不是单个对象时，认为是批量插入，替换对象集合中的主键为雪花算法
                    List list = (List) ((Map) args[1]).get("list");
                    for (Object obj : list) {
                        setProperty(obj, primaryKey, snowflakeIdWorker.nextId());
                    }
                } else {
                    setProperty(args[1], primaryKey, snowflakeIdWorker.nextId());
                }
            }
        }

        return invocation.proceed();
    }

    @Override
    public Object plugin(Object o) {

        return Plugin.wrap(o, this);
    }


    /**
     * 设置对象属性值
     *
     * @param obj      对象
     * @param property 属性名称
     * @param value    属性值
     */
    private void setProperty(Object obj, String property, Object value)
            throws NoSuchFieldException,
            IllegalAccessException,
            InvocationTargetException {
        Field field = obj.getClass().getDeclaredField(property);
        ReflectionUtils.makeAccessible(field);
        BeanUtils.setProperty(obj, property, value);
    }

    public void setSnowflakeIdWorker(SnowflakeIdWorker snowflakeIdWorker) {
        this.snowflakeIdWorker = snowflakeIdWorker;
    }


    public void setPrimaryKey(String primaryKey) {
        this.primaryKey = primaryKey;
    }
}
